<%@page import="java.text.DecimalFormat"%>
<%@page import="edu.mta.pokerstats.Game"%>
<%@page import="edu.mta.pokerstats.GameRecord"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Map"%>
<%@page import="edu.mta.pokerstats.Player"%>
<%@page import="edu.mta.pokerstats.Team"%>
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	Player viewingPlayer = (Player)session.getAttribute("viewingPlayer");
	Team playerTeam = Team.getTeamById(viewingPlayer.getTeamId());
	Map<Integer,Game> teamGames = playerTeam.getGamesOfTeam();
	int totalGames = teamGames.size();
	ArrayList<Player> playersList = playerTeam.getPlayersInTeam();
	int minNumOfGames;
	try {
		minNumOfGames = Integer.parseInt(request.getParameter("minNumOfGames"));
	} catch (Exception e) {
		minNumOfGames = 0;
	} 
%>
<script type="text/javascript">
	$(document).ready(function () {
		$('#PlayersTable').dataTable({
			"iDisplayLength": 50,
		    "aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
			"aaSorting": [[5, "desc"]],
			"aoColumnDefs": [
					{ 'bSortable': false, 'aTargets': [9] },
					{ 'bSearchable': false, 'aTargets': [9]}
			]
		});
	} );
	
	function refreshResults(){
		spinnerObject.spin(document.getElementById('thresholdSubmit'));
		$.ajax({
			url : "ShowPlayersInTeam.jsp",
			type : "POST",
			data : {
				minNumOfGames : $("#minGamesThreshold").val()
			},
			success : function(data, status) {
				spinnerObject.stop();
				changeDivMainContainer(data);
			}
		});
	}

	function displayPlayer(i_PlayerID){
		$.ajax({
			url : "ShowSinglePlayerRecords.jsp",
			type : "POST",
			data : {
				viewerID : <%=viewingPlayer.getId()%>,
				playerID : i_PlayerID
			},
			success : function(data, status) {
				changeDivMainContainer(data);
			}
		});
	}
	<%if (viewingPlayer.isTeamLeader()){%>
	function kickPlayerFromTeam(i_PlayerID, i_RowNum){
		if (confirm("About to kick a player out of your team!"))
			{
				$.ajax({
					url : "servletPlayer",
					type : "POST",
					data : {
						action : "changeJoinStatus",
						playerID : i_PlayerID,
						joinStatus : "Declined"
					},
					success : function(data, status) {
						$("#row"+i_RowNum).fadeOut();
					}
				});
			}
	}
	<%}%>
	</script>
<h3>Players in Team "<%=playerTeam.getName()%>"</h3>
<label>View players with minimum number of games :</label>
<input type="number" id="minGamesThreshold" min="0" value="<%=minNumOfGames%>"/>
<button class="yellowButton" id="thresholdSubmit" onClick="refreshResults()">View Results</button>
<br>
<table id="PlayersTable" class="display">
	<thead>
		<tr>
			<th>Name</th>
			<th>Birthday</th>
			<th>Games Played</th>
			<th>Total Invested</th>
			<th>Total Winning</th>
			<th>Current Balance</th>
			<th>Knockouts</th>
			<th>Average Position</th>
			<th>Rank</th>
			<th>Actions</th>
		</tr>
	</thead>
	<tbody>
		<%
			DecimalFormat twoDForm = new DecimalFormat("#.##");
			for (int i = 0; i < playersList.size(); i++) {
				int totalInvested = 0;
				int totalWinnings = 0;
				int sumOfPosition = 0;
				int gamesPlayed = 0;
				int totalKOs = 0;
				double avgPosition = 0;
				double personalRank = 0;
				Player currPlayer = playersList.get(i);
				ArrayList<GameRecord> playerRecords = currPlayer.GetGameRecordsForPlayer();
				for (GameRecord gr : playerRecords) {
					Game currGame = teamGames.get(gr.getGameId());
					gamesPlayed++;
					totalInvested += currGame.getCostOfBuyIn();
					totalInvested += gr.getNumberOfRebuys() * currGame.getCostOfRebuy();
					totalWinnings += gr.getWonInGame();
					sumOfPosition += gr.getPosition();
					totalKOs += gr.getKnockouts();
				}
				if (gamesPlayed < minNumOfGames){
					continue;
				}
				if (gamesPlayed > 0){
					avgPosition = sumOfPosition / (double) gamesPlayed;
					personalRank = avgPosition * (totalGames / (double)gamesPlayed);
				}
		%>
		<tr id="row<%=i + 1%>">
		<td><%=currPlayer.getName()%></td>
		<td class="noWrap"><%= currPlayer.getBirthday() != null? currPlayer.getBirthday() : "Unknown"%></td>
		<td><%=gamesPlayed%></td>
		<td><%=totalInvested%></td>
		<td><%=totalWinnings%></td>
		<td><%=totalWinnings - totalInvested%></td>
		<td><%=totalKOs%></td>
		<td><%=avgPosition > 0 ? twoDForm.format(avgPosition) : ""%></td>
		<td><%=personalRank > 0 ? twoDForm.format(personalRank): ""%></td>
		<td>
		<% if (viewingPlayer.isTeamLeader()){%>
			<button <%=currPlayer.isTeamLeader()? "title=\"Cannot kick Team Leader\" disabled=\"disabled\" " : ""%> onclick="kickPlayerFromTeam(<%=currPlayer.getId()%>,<%=i + 1%>)">Kick Player</button>
		<%}%>
			<button onclick="displayPlayer(<%=currPlayer.getId()%>)">View Player Info</button>
		</td>
	</tr>
	<%
		}
	%>
	</tbody>
</table>